package edu.scut.dap.server;

import edu.scut.dap.service.TaskCMService;
import edu.scut.dap.service.TaskCMServiceImpl;
import org.apache.log4j.Logger;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TSimpleServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;

import java.util.Date;

/**
 * Created by Alex on 2016/12/3.
 */
public class TaskcmServer {

    private static TaskcmServer instance;
    private static Logger logger = Logger.getLogger(TaskcmServer.class);

    private TaskcmServer() {
    }

    public static TaskcmServer getInstance() {
        if (instance == null) {
            synchronized (TaskcmServer.class) {
                if (instance == null) {
                    instance = new TaskcmServer();
                    return instance;
                }
            }
        }
        return instance;
    }

    public void init() {
        try {
            int port = 9876;
            TServerSocket serverSocket = new TServerSocket(port);
            logger.info("Startup server in port: " + port);

            TServer.Args targs = new TServer.Args(serverSocket);
            targs.processor(new TaskCMService.Processor<TaskCMService.Iface>(new TaskCMServiceImpl()));
            targs.protocolFactory(new TBinaryProtocol.Factory());

            TServer tserver = new TSimpleServer(targs);
            logger.info("Prepared to serve");
            tserver.serve();
        } catch (TTransportException e) {
            logger.error("Fail to startup server");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        logger.info("Startup server at: " + new Date().toLocaleString());
        TaskcmServer server = TaskcmServer.getInstance();
        server.init();
        logger.info("Shutdown server at: " + new Date().toLocaleString());
    }
}
